package com.zhang.crowd.mvc.handler;

import com.github.pagehelper.PageInfo;
import com.zhang.crowd.entity.Role;
import com.zhang.crowd.service.api.RoleService;
import com.zhang.crowd.util.ResultEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
public class RoleHandler {
    @Autowired
    RoleService roleService;

    @PreAuthorize("hasRole('部长') or hasRole('经理')")
    @ResponseBody
    @RequestMapping("/role/get/page/info.json")
    public ResultEntity<PageInfo<Role>> getPageInfo(
            @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
            @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize,
            @RequestParam(value = "keyword", defaultValue = "") String keyword
    ){
        //调用Service方法获取分页数据
        PageInfo<Role> pageInfo = roleService.getPageInfo(pageNum, pageSize,keyword);

        //封装到ResultEntity对象中返回（如果上面的操作抛出异常，交给异常映射机制来处理）
       return ResultEntity.successWithData(pageInfo);
    }
    @PreAuthorize("hasRole('部长')")
    @ResponseBody
    @RequestMapping("/role/save.json")
    public ResultEntity<String> addRole(Role role){

        roleService.saveRole(role);

        return ResultEntity.successWithoutData();

    }
    @PreAuthorize("hasRole('部长')")
    @ResponseBody
    @RequestMapping("role/update.json")
    public ResultEntity<String> update(Role role){
        System.out.println(role);
       roleService.updateRole(role);

       return ResultEntity.successWithoutData();
    }
    @PreAuthorize("hasRole('部长')")
    @ResponseBody
    @RequestMapping("/role/remove/by/role/id/array.json")
    public ResultEntity<String> removeByRoleIdArray(@RequestBody List<Integer> roleList){

        System.out.println("=============================");
        System.out.println(" ");
        System.out.println(" ");
        System.out.println(" ");
        System.out.println(" ");
        System.out.println(roleList);
        System.out.println(" ");
        System.out.println(" ");
        System.out.println(" ");
        System.out.println(" ");
        System.out.println("=============================");
        roleService.removeRole(roleList);
        return ResultEntity.successWithoutData();
    }
}
